package com.qiguliuxing.dts.db.service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import com.qiguliuxing.dts.db.dao.DtsPermissionMapper;
import com.qiguliuxing.dts.db.domain.DtsPermission;

@Service
public class DtsPermissionService {
	@Resource
	private DtsPermissionMapper permissionMapper;

	public Set<String> queryByRoleIds(Integer[] roleIds) {
		Set<String> permissions = new HashSet<String>();
		if (roleIds.length == 0) {
			return permissions;
		}

		QueryWrapper<DtsPermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().in(DtsPermission::getRoleId, roleIds);
		queryWrapper.lambda().eq(DtsPermission::getDeleted, false);
		List<DtsPermission> permissionList = permissionMapper.selectList(queryWrapper);

		for (DtsPermission permission : permissionList) {
			permissions.add(permission.getPermission());
		}

		return permissions;
	}

	public Set<String> queryByRoleId(Integer roleId) {
		Set<String> permissions = new HashSet<String>();
		if (roleId == null) {
			return permissions;
		}

		QueryWrapper<DtsPermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsPermission::getRoleId, roleId);
		queryWrapper.lambda().eq(DtsPermission::getDeleted, false);
		List<DtsPermission> permissionList = permissionMapper.selectList(queryWrapper);

		for (DtsPermission permission : permissionList) {
			permissions.add(permission.getPermission());
		}

		return permissions;
	}

	public boolean checkSuperPermission(Integer roleId) {
		if (roleId == null) {
			return false;
		}

		QueryWrapper<DtsPermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsPermission::getRoleId, roleId);
		queryWrapper.lambda().eq(DtsPermission::getPermission, "*");
		queryWrapper.lambda().eq(DtsPermission::getDeleted, false);
		return permissionMapper.selectCount(queryWrapper) != 0;
	}

	public void deleteByRoleId(Integer roleId) {
		QueryWrapper<DtsPermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsPermission::getRoleId, roleId);
		queryWrapper.lambda().eq(DtsPermission::getDeleted, false);
		permissionMapper.delete(queryWrapper);
	}

	public void add(DtsPermission DtsPermission) {
		DtsPermission.setAddTime(LocalDateTime.now());
		DtsPermission.setUpdateTime(LocalDateTime.now());
		permissionMapper.insert(DtsPermission);
	}
}
